package com.lei.sort;


import java.lang.reflect.*;

/**
 * @Author LeiXiaoLei
 * @Date 2022/7/14 19:32
 * @Version 1.0
 */
public class SortingHelper {
    private SortingHelper() {
    }

    public static <E extends Comparable<E>> boolean isSorted(E[] arr) {
        for (int i = 1; i < arr.length; i++) {
            if (arr[i - 1].compareTo(arr[i]) > 0)
                return false;
        }
        return true;
    }


    public static <E extends Comparable<E>> void sortTest(Class<?> clazz, E[] arr) {
        long startTime = System.nanoTime();
        String[] split = clazz.toString().split("\\.");
        String sortName = split[split.length - 1];
        try {
            for (Method method : clazz.getMethods()) {
                if (method.getName().equals("sort")) {
                    method.invoke(null, (Object) arr);
//                    Type[] genericParameterTypes = method.getGenericParameterTypes();
//                    for (Type genericParameterType : genericParameterTypes) {
//                        System.out.println("方法参数type:" + genericParameterType);
//                    }
                }
            }
            long endTime = System.nanoTime();
            double time = (endTime - startTime) / 1000000000.0;

            if (!SortingHelper.isSorted(arr)) {
                throw new RuntimeException(sortName + " failed");
            }
            System.out.printf("%s -> n = %d : %f s%n", sortName, arr.length, time);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
